package com.xuanzheng.company.servlet;

import com.google.gson.Gson;
import com.xuanzheng.company.entity.User;
import com.xuanzheng.company.service.AIService;
import com.xuanzheng.company.service.impl.AIServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * AI使用信息Servlet
 */
@WebServlet("/aiUsageInfo")
public class AIUsageInfoServlet extends HttpServlet {
    
    private final AIService aiService = new AIServiceImpl();
    private final Gson gson = new Gson();
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        
        response.setContentType("application/json;charset=UTF-8");
        response.setHeader("Cache-Control", "no-cache");
        
        PrintWriter out = response.getWriter();
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 检查用户是否登录
            HttpSession session = request.getSession(false);
            if (session == null) {
                result.put("remainingQuestions", "未登录");
                result.put("currentModel", "未知");
                out.print(gson.toJson(result));
                return;
            }
            
            User user = (User) session.getAttribute("user");
            if (user == null) {
                result.put("remainingQuestions", "未登录");
                result.put("currentModel", "未知");
                out.print(gson.toJson(result));
                return;
            }
            
            // 获取用户使用信息
            result = aiService.getUserUsageInfo(user.getId());
            
        } catch (Exception e) {
            e.printStackTrace();
            result.put("remainingQuestions", "错误");
            result.put("currentModel", "未知");
        }
        
        out.print(gson.toJson(result));
        out.flush();
        out.close();
    }
}